package cn.lyf.service;

import cn.lyf.dao.BlogDao;
import cn.lyf.dao.BlogTypeDao;
import cn.lyf.dao.BodyDao;
import cn.lyf.entity.Blog;
import cn.lyf.entity.BlogType;
import cn.lyf.entity.Body;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BlogServiceImpl implements BlogService {
    @Autowired
    BodyDao bodyDao;

    @Autowired
    BlogDao blogDao;

    @Autowired
    BlogTypeDao blogTypeDao;

    //添加博客
    //content:博客内容
    @Override
    public void add(Body body, Blog blog) {
        //获取新添加博客内容的id
        String bodyid = bodyDao.add(body);
        //把bodyid赋值给blog
        blog.setBodyid(bodyid);
        BlogType blogType =  blogTypeDao.findById(blog.getBlogtypeid());
        blogType.setNum(blogType.getNum()+1);
        blogDao.add(blog);
        blogTypeDao.add(blogType);
    }


    @Override
    public List<Blog> findBlogsByTypeId(String typeid) {
        return blogDao.findBlogsByTypeId(typeid);
    }

    @Override
    public Map<String, Object> findOneBlog(String blogid) {
        Blog blog = blogDao.findOneBlog(blogid);
        System.out.println("bodyid=="+blog.getBodyid());
        Body body = bodyDao.findOneBody(blog.getBodyid());
        Map<String,Object> respMap = new HashMap<>();
        respMap.put("blog",blog);
        respMap.put("body",body);
        return respMap;
    }

    @Override
    public List<Blog> findBlogsByTitle(String title) {
        return blogDao.findBlogsByTitle(title);
    }

    @Override
    public void addReadnum(String blogid) {
        Blog blog = blogDao.findOneBlog(blogid);
        blog.setReadnum(blog.getReadnum()+1);
        blogDao.add(blog);
    }

    @Override
    public int addLike(String blogid,String userid) {
        Blog blog = blogDao.findOneBlog(blogid);
        List<String> likeusers = blog.getLikeusers();
        if(likeusers!=null&&likeusers.contains(userid))return 0;
        if(likeusers==null){
            likeusers = new ArrayList<>();
        }
        blog.setLikenum(blog.getLikenum()+1);
        likeusers.add(userid);
        blog.setLikeusers(likeusers);
        blogDao.add(blog);
        return 1;
    }
}
